/**
 * @Author:  renyc
 * @Date: 2022-11-30 16:36:13
 */

import * as Cesium from 'cesium/Cesium';
import EventType from "./EventType"

class Event{

    constructor(){
        /**
         * 事件的缓存注销
         */
        this._cache = {};
        this._registerEvents();
    }

    /**
     * 注册事件
     * @param {EventType} type 
     */
    register(type){
        this._cache[type] = new Cesium.Event();
    }

    /**
     * 注册事件
     * 派生类实现该函数，为每一个具体的EventType，注册一个Cesium.Event。然后再关联监听器。
     */
    _registerEvents(){}

    /**
     * 注册Event，注册后的事件可以重复触发
     * @param {EventType} type 
     * @param {Function} listener 
     * @param {Object} context 
     * @returns Cesium.Event.RemoveCallback或undefined
     */
    on(type, listener, context){
        let event = this.getEvent(type);
        if(event || listener){
            let scope = context || this
            let removeCallback = event.addEventListener(listener, scope);
            return removeCallback;
        }
    }

    /**
     * 注册Event，注册后的事件只能触发一次
     * @param {EventType} type 
     * @param {Function} listener 
     * @param {Object} context 
     */
    once(type, listener, context){
        
    }

    /**
     * 注销Event
     * @param {EventType} type 
     * @param {Function} listener 
     * @param {Object} context
     * @returns {boolean} true 成功删除
     */
    off(type, listener, context){
        let event = this.getEvent(type);
        let removed = false;
        if(event || listener){
            let scope = context || this
            removed = event.removeEventListener(listener, scope);
        }
        return removed;
    }

    /**
     * 触发事件
     * 调用Cesium.Event的raiseEvent方法触发事件响应
     * @param {*} type 
     * @param {*} params 
     */
    fire(type, params){
        let event = this.getEvent(type);
        if(event){
            event.raiseEvent(params);
        }
    }

    /**
     * 根据EventType在_cache中查找对应的Event
     * @param {EventType} type 
     * @returns Cesium.Event对象，若未找到则返回undefined
     */
    getEvent(type){
        return this._cache[type] || undefined;
    }
}

export default Event